package org.swim.servlet;

import java.io.IOException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.swim.entity.User;
import org.swim.session.UserManagerRemote;

/**
 * Servlet implementation class EditProfile
 */
public class EditProfile extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditProfile() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        request.setAttribute("profileToEdit", request.getParameter("profile"));
		request.getRequestDispatcher("WEB-INF/EditProfile.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String avatar = request.getParameter("avatar");
        HttpSession session = request.getSession();
        User me = (User) session.getAttribute("user");
        InitialContext ic;
        try {
        	ic = new InitialContext();
        	UserManagerRemote userManager = (UserManagerRemote) ic.lookup("UserManagerRemote");
	        if(avatar.length()>0){
	        	userManager.changeAvatar(me.getId(), avatar);
	        }
        } catch (NamingException e) {
        	e.printStackTrace();
        }
		request.getRequestDispatcher("Profile?id=" + me.getId()).forward(request, response);
	}

}
